from PySide6.QtWidgets import QListWidget
from PySide6.QtCore import Qt, QMimeData, QByteArray
from PySide6.QtGui import QDrag, QPixmap, QColor, QPainter


class DraggableListWidget(QListWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setDragEnabled(True)
        self.setDragDropMode(QListWidget.DragOnly)
        self.setSelectionMode(QListWidget.SingleSelection)

    def mouseMoveEvent(self, event):
        """鼠标移动事件，开始拖拽"""
        if event.buttons() == Qt.LeftButton:
            # 获取当前选中的项
            currentItem = self.currentItem()
            if currentItem is None:
                return

            # 创建拖拽对象
            drag = QDrag(self)
            mimeData = QMimeData()

            # 获取节点类型数据
            nodeType = currentItem.data(Qt.UserRole)

            # 设置 MIME 数据
            mimeData.setData("application/x-audionode", QByteArray(nodeType.encode('utf-8')))
            mimeData.setText(currentItem.text())

            drag.setMimeData(mimeData)

            # 创建拖拽预览图像
            pixmap = self.createDragPixmap(currentItem.text())
            drag.setPixmap(pixmap)
            drag.setHotSpot(pixmap.rect().center())

            # 开始拖拽
            drag.exec_(Qt.CopyAction)
        else:
            super().mouseMoveEvent(event)

    def createDragPixmap(self, text):
        """创建拖拽预览图像"""
        # 创建一个简单的预览图像
        pixmap = QPixmap(100, 40)
        pixmap.fill(QColor(60, 60, 60, 200))  # 半透明背景

        painter = QPainter(pixmap)
        painter.setPen(QColor(255, 255, 255))
        painter.drawText(pixmap.rect(), Qt.AlignCenter, text)
        painter.end()

        return pixmap